<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java面试,">










<meta name="description" content="本文学习《剑指Java面试-Offer直通车》第十一章，主要内容为: Spring框架相关知识视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta name="keywords" content="Java面试">
<meta property="og:type" content="article">
<meta property="og:title" content="【三】剑指Java面试Offer直通车-Spring框架相关知识">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/20/java-interview-offer-3/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文学习《剑指Java面试-Offer直通车》第十一章，主要内容为: Spring框架相关知识视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220180112634.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222064249310.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222064444867.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222064820767.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222064947754.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222065312248.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222071648597.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222070505454.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222071359182.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191223062019159.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191223063721026.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224062203009.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224062641238.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224063054543.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224064830604.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224065100847.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230062309438.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230062719250.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230053954171.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230055634288.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230064112878.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230094023151.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230105413609.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230111047099.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230111549489.jpg">
<meta property="og:updated_time" content="2019-12-30T03:16:15.325Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【三】剑指Java面试Offer直通车-Spring框架相关知识">
<meta name="twitter:description" content="本文学习《剑指Java面试-Offer直通车》第十一章，主要内容为: Spring框架相关知识视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191220180112634.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/20/java-interview-offer-3/">





  <title>【三】剑指Java面试Offer直通车-Spring框架相关知识 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/20/java-interview-offer-3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【三】剑指Java面试Offer直通车-Spring框架相关知识</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-20T05:59:13+08:00">
                2019-12-20
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java基础/" itemprop="url" rel="index">
                    <span itemprop="name">Java基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文学习《剑指Java面试-Offer直通车》第十一章，主要内容为: Spring框架相关知识<br>视频课程地址：<a href="https://coding.imooc.com/class/303.html" target="_blank" rel="noopener">https://coding.imooc.com/class/303.html</a><br>项目代码地址：<a href="https://gitee.com/aiolos123/java_basic" target="_blank" rel="noopener">https://gitee.com/aiolos123/java_basic</a></p>
<a id="more"></a>

<h2 id="Spring家族的介绍"><a href="#Spring家族的介绍" class="headerlink" title="Spring家族的介绍"></a>Spring家族的介绍</h2><p><strong>精通一个经典框架的架构和原理，其他的框架就容易掌握了</strong></p>
<ol>
<li>如何选择和学习框架<blockquote>
<p>对应的开发者社区是否有名、是否活跃；框架的模块是否不断迭代</p>
</blockquote>
</li>
</ol>
<p>————spring框架就是这样的一个经典框架</p>
<ol start="2">
<li>Spring家族<blockquote>
<p>SpringCore、SpringData、SpringBoot、SpringCloud、SpringCloudDataFlow等等</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191220180112634.jpg" alt="Spring家族"></p>
<ol start="3">
<li>由于Spring家族内容众多，本课程的面试点只能重点进攻某些核心内容</li>
</ol>
<h2 id="Spring-IOC原理"><a href="#Spring-IOC原理" class="headerlink" title="Spring IOC原理"></a>Spring IOC原理</h2><ol>
<li>IOC是什么<br>IOC (Inversion of Control): 控制反转。Spring Core最核心的部分，是Spring家族所有组件的基础。<br>IOC是一种思想，而不是一种技术。</li>
</ol>
<h3 id="什么是DI"><a href="#什么是DI" class="headerlink" title="什么是DI"></a>什么是DI</h3><blockquote>
<p>要理解IOC，先要了解依赖注入 (Dependency Inversion)设计思想<br>DI: 把底层类作为参数传递给上层类，实现上层对下层的“控制”</p>
</blockquote>
<ol>
<li>传统设计方式：上层建筑依赖下层建筑<blockquote>
<p>要设计行李箱，就要先设计轮子，根据轮子设计底盘，依次类推最终完成行李箱的设计。这里存在一个依赖关系，如下图：</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191222064249310.jpg" alt="传统设计方式"></p>
<ol start="2">
<li><p>传统设计方式的缺点：可维护性差————如果轮子的需求方式变化，则上层全部都得修改一遍<br><img src="/blog/images/20191222064444867.jpg" alt="传统设计方式的缺点"></p>
</li>
<li><p>DI设计方式</p>
<blockquote>
<p>先设计行李箱大小，根据行李箱大小设计箱体，依次类推最后设计轮子。 轮子依赖于底盘<br>DI: 把底层类作为参数传递给上层类，实现上层对下层的“控制”</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191222064820767.jpg" alt="DI设计方式"></p>
<ol start="4">
<li>DI设计方式的优点：如果轮子的需求发生变化，仅需修改该类，其他上层无需修改<blockquote>
<p>并且有利于分工协作；单元测试</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191222064947754.jpg" alt="DI设计方式的优点"></p>
<h3 id="什么是IOC"><a href="#什么是IOC" class="headerlink" title="什么是IOC"></a>什么是IOC</h3><ol>
<li>DI和IOC的关系<blockquote>
<p>IOC的两种实现方式：DI和DL。 DI是Spring使用的方式，也是主流方式</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191222065312248.jpg" alt="DI和IOC的关系"></p>
<ol start="2">
<li><p>DI(依赖注入)的四种方式<br>从上图可知，有四种DI方式</p>
<blockquote>
<p>setter、interface、constructor、annotation</p>
</blockquote>
</li>
<li><p>依赖倒置原则、ICO、DI、IOC容器的关系</p>
</li>
</ol>
<p><img src="/blog/images/20191222071648597.jpg" alt="依赖倒置原则、ICO、DI、IOC容器的关系"></p>
<blockquote>
<p>依赖倒置原则: 上层不应该依赖下层，它们都应该依赖其抽象的设计思想<br>IOC：实现依赖倒置原则的思路<br>DI： 实现IOC的方法<br>IOC容器：Spring框架基于IOC提出的容器；对于IOC而言，最重要的就是IOC容器，因为它管理着Bean的生命周期，控制着Bean的依赖注入；</p>
</blockquote>
<ol start="4">
<li>IOC容器<br><img src="/blog/images/20191222070505454.jpg" alt="IOC容器的作用"></li>
</ol>
<p>IOC容器的优点：因为依赖注入所以就需要写大量的new来初始化对象，而IOC容器能自动对对象完成初始化，只需维护一个Configuration(xml或Configuration类)即可，避免在各处使用new来创建类，并且可以做到统一维护；创建实例对象时不需要了解其中的细节；</p>
<p><img src="/blog/images/20191222071359182.jpg" alt="IOC容器的优点"></p>
<h3 id="Spring-IOC容器"><a href="#Spring-IOC容器" class="headerlink" title="Spring IOC容器"></a>Spring IOC容器</h3><ol>
<li>Spring IOC容器的工作过程</li>
</ol>
<blockquote>
<p>a. Spring启动时读取Bean的配置信息，并在Spring IOC容器中生成一份Bean配置的注册表<br>b. 根据Bean配置注册表实例化bean，并装配好Bean之间的依赖关系<br>c. 将Bean实例放到Spring IOC容器中，供上层应用程序使用。 全过程如下图：</p>
</blockquote>
<p><img src="/blog/images/20191223062019159.jpg" alt="Spring IOC容器"></p>
<ol start="2">
<li><p>Spring提供一个Bean的配置文件，来描述Bean及Bean之间的依赖关系。利用Java语言的反射来实例化Bean并<br>建立Bean之间的依赖关系。</p>
</li>
<li><p>SpringIOC支持以下功能(最重要的功能是依赖注入和自动装配)</p>
<blockquote>
<p><strong>依赖注入；</strong>依赖检查；<strong>自动装配；</strong>支持集合；指定初始化方法和销毁方法；支持回调方法(需要实现Spring接口，因有侵入性应谨慎使用)</p>
</blockquote>
</li>
<li><p>Spring如何设计容器</p>
<blockquote>
<p>SpringIOC通过两个核心接口来表示容器：BeanFactory、ApplicationContext</p>
</blockquote>
</li>
<li><p>介绍SpringIOC两个核心接口之前的铺垫(Spring中核心接口和类)</p>
<blockquote>
<p>a. Spring的Bean:<br>b. BeanDefinition:  主要用来描述Bean的定义。SpringIOC启动时会将xml文件或注解的Bean定义解析为Spring内部的BeanDefinition</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191223063721026.jpg" alt="BeanDefinition"></p>
<blockquote>
<p>c. BeanDefinitionRegistry: 提供向IOC容器手工注册BeanDefinition对象的方法。创建SpringBoot2.1.2的项目，分析BeanDefinitionRegistry源码，如下图：</p>
</blockquote>
<p><img src="/blog/images/20191224062203009.jpg" alt="创建SpringBoot2.1.2的项目，分析源码"></p>
<blockquote>
<p>d. BeanFactory: 是Spring框架最核心的接口，提供IOC的配置机制；包含Bean的各种定义，便于实例化Bean；还能在Bean实例化时建立Bean之间的依赖关系；Bean生命周期的控制。BeanFactory体系结构如下图：</p>
</blockquote>
<p><img src="/blog/images/20191224062641238.jpg" alt="BeanFactory体系结构"><br>BeanFactory的源码如下：<br><img src="/blog/images/20191224063054543.jpg" alt="BeanFactory的源码"></p>
<blockquote>
<p>e. 在SpringIOC在默认情况下Bean都是以单例形式存在的。即使用getBean()方法返回的都是同一个实例</p>
</blockquote>
<ol start="6">
<li>BeanFactory与ApplicationContext的比较</li>
</ol>
<table>
<thead>
<tr>
<th>比较</th>
<th>BeanFactory</th>
<th>ApplicationContext</th>
</tr>
</thead>
<tbody><tr>
<td>关系</td>
<td>由于BeanFactory的功能还不够强大，因此Spring在BeanFactory的基础上设计了功能更强大的接口————ApplicationContext</td>
<td>ApplicationContext是BeanFactory的子接口。在Spring体系中，BeanFactory与ApplicationContext是最重要的接口。我们使用SpringIOC容器时，大部分都是ApplicationContext接口的实现类</td>
</tr>
<tr>
<td>服务对象不同</td>
<td>BeanFactory是Spring框架的基础设施，面向Spring本身</td>
<td>ApplicationContext面向使用Spring框架的开发者</td>
</tr>
<tr>
<td>举例说明</td>
<td>如果SpringIOC是汽车，则BeanFactory是发动机</td>
<td>如果SpringIOC是汽车，则ApplicationContext是一辆完整的汽车，包含发动机、驾驶员使用的方向盘、离合器等操作汽车的组件。代表了SpringIOC容器的全部功能。</td>
</tr>
<tr>
<td>功能不同</td>
<td>是Spring框架最核心的接口，提供IOC的配置机制；包含Bean的各种定义，便于实例化Bean；还能在Bean实例化时建立Bean之间的依赖关系；Bean生命周期的控制。</td>
<td>ApplicationContext继承多个接口，功能有：管理、装配Bean(继承了BeanFactory)、加载资源文件(继承了ResourcePatternResolver)、实现国际化等功能(继承了MessageSource)、注册监听器、实现监听机制(继承了ApplicationEventPublisher)</td>
</tr>
</tbody></table>
<ol start="7">
<li><p>Spring顶层接口的UML图如下：<br><img src="/blog/images/20191224064830604.jpg" alt="Spring顶层接口的UML图"></p>
</li>
<li><p>SpringBoot中默认的ApplicationContext源码分析如下图(SpringBoot的IOC容器默认就是ApplicationContext的子类AnnotationConfigServletWebServerApplicationContext)<br><img src="/blog/images/20191224065100847.jpg" alt="SpringBoot中默认的ApplicationContext源码分析"></p>
</li>
</ol>
<h3 id="Bean实例如何装载到IOC容器中"><a href="#Bean实例如何装载到IOC容器中" class="headerlink" title="Bean实例如何装载到IOC容器中"></a>Bean实例如何装载到IOC容器中</h3><ol>
<li>Bean实例装载到IOC容器中的两种方法<blockquote>
<p>a. 方法一：注解方式————通过在配置类中上添加@Configuration注解，在其方法上添加@Bean注解来创建并声明Bean实例注入到SpringIOC容器中<br>@Configuration的作用：声明一个配置类；将@Bean注解的实例注入到IOC容器中;<br>该配置类的作用：告诉IOC容器如何装配PersonOne这个Bean</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191230062309438.jpg" alt="注解方式"></p>
<blockquote>
<p>b. 方法二：以SpringBoot的方式扫描装配————通过在bean类上添加@Component，在启动类上添加@ComponentScan(@SpringBootApplication中已包含该注解)</p>
</blockquote>
<p><img src="/blog/images/20191230062719250.jpg" alt="扫描装配"></p>
<ol start="2">
<li><p>如何从IOC容器中获取Bean实例并使用</p>
<figure class="highlight d"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> OfferApplication &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> main(String[] args) &#123;</span><br><span class="line">        ApplicationContext ctx = SpringApplication.run(OfferApplication.<span class="keyword">class</span>, args);</span><br><span class="line">        <span class="comment">//在IOC容器中获取bean, 根据类型获取Bean</span></span><br><span class="line">        Person person = ctx.getBean(Person.<span class="keyword">class</span>);</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"name is "</span> + person.getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>如何实现依赖注入: 通过在bean类上添加@Component，在bean的实例上添加@Autowired，实现依赖注入<br><img src="/blog/images/20191230053954171.jpg" alt="如何实现依赖注入"></p>
</li>
<li><p>@Autowired是根据类型注入，所以如果在项目中有多个Pet接口的实现，则使用@Autowired就会报错，这时就需要使用@Primary或 @Qualifier注解<br><img src="/blog/images/20191230055634288.jpg" alt="如何实现依赖注入"></p>
</li>
</ol>
<h3 id="SpringIOC的refresh源码解析"><a href="#SpringIOC的refresh源码解析" class="headerlink" title="SpringIOC的refresh源码解析"></a>SpringIOC的refresh源码解析</h3><p>???</p>
<h3 id="SpringIOC的getBean方法的解析"><a href="#SpringIOC的getBean方法的解析" class="headerlink" title="SpringIOC的getBean方法的解析"></a>SpringIOC的getBean方法的解析</h3><blockquote>
<p>见AbstactBeanFactory</p>
</blockquote>
<p>getBean方法的代码逻辑：</p>
<ol>
<li>转换beanName</li>
<li>从缓存中加载实例</li>
<li>实例化Bean</li>
<li>检测parentBeanFactory</li>
<li>初始化依赖的Bean</li>
<li>创建Bean</li>
</ol>
<h3 id="SpringIOC相关面试题"><a href="#SpringIOC相关面试题" class="headerlink" title="SpringIOC相关面试题"></a>SpringIOC相关面试题</h3><ol>
<li>Spring Bean的五个作用域<blockquote>
<p>a. singleton：Spring的默认作用域，每个SpringIOC容器里拥有唯一的一个Bean实例<br>b. prototype：针对每个getBean请求，容器都会创建一个bean实例<br>c. request: 会为每个Http请求创建一个Bean实例<br>d. session: 会为每个session创建一个Bean实例。该Bean是专属某个session使用的<br>e. globalSession：会为每个全局HTTP Session创建一个Bean实例，该作用域仅对Protlet有效</p>
</blockquote>
</li>
</ol>
<p>后三种是Web容器所支持的。 </p>
<ol start="2">
<li>Spring Bean的生命周期<br><img src="/blog/images/20191230064112878.jpg" alt="Spring Bean的生命周期"></li>
</ol>
<h2 id="AOP的介绍和使用"><a href="#AOP的介绍和使用" class="headerlink" title="AOP的介绍和使用"></a>AOP的介绍和使用</h2><ol>
<li><p>软件工程的一个基本原则————关注点分离： 不同的问题交给不同的部分去解决，每部分专注于解决自己的问题。 AOP正是此种技术的实现。</p>
<blockquote>
<p>我们的代码主要是某种特定的业务逻辑的实现，但我们在实现业务逻辑时也要实现事务管理、日志管理、缓存管理等通用化功能。并且通用化的功能要和业务代码混合在一起。所以为了让业务功能代码的关注点和通用化功能代码的关注点分离开，就出现了AOP的技术。</p>
</blockquote>
</li>
<li><p>通用化功能代码的实现，就是所谓的切面(Aspect),如事务管理、日志管理、缓存管理等</p>
</li>
<li><p>业务功能代码和切面代码分开后，职责明确，开发者的关注点专一，架构将变得高内聚低耦合</p>
</li>
<li><p>如何确保功能的完整性：切面最终需要被合并到业务中，称为织入(Weave)。</p>
</li>
<li><p>AOP的三种织入方式</p>
<blockquote>
<p>编辑时织入: 在代码编译时合并切面代码，生成完整功能的字节码，这需要特殊的Java编译器，如AspectJ<br>类加载时织入：需要特殊的Java编译器，如AspectJ和AspectWerkz<br>运行时织入： Spring采用的方式，通过动态代理的方式调用切面代码，增强业务功能，无需特殊的Java编译器即可实现</p>
</blockquote>
</li>
<li><p>运行时织入的代码示例</p>
<blockquote>
<p>使用AOP(织入切面)的方法——www：what(AOP的功能是什么)、where(在何处织入)、when(在何时织入)。代码如下：</p>
</blockquote>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 请求日志的切面————what</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Aspect</span>作用:将一个类定义为切面类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RequestLogAspect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger =</span><br><span class="line">            LoggerFactory.getLogger(RequestLogAspect.class);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义切入点————where: 在执行com.aiolos.aop.controller包下所有public的方法时织入</span></span><br><span class="line">    <span class="meta">@Pointcut</span>(<span class="string">"execution(public * com.aiolos.offer.aop.controller..*.*(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">webLog</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义何时织入————when: @Before()是在切入点webLog()执行之前织入如下的业务:记录日志</span></span><br><span class="line">    <span class="meta">@Before</span>(<span class="string">"webLog()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doBefore</span><span class="params">(JoinPoint joinPoint)</span></span>&#123;</span><br><span class="line">        <span class="comment">//接收到请求</span></span><br><span class="line">        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();</span><br><span class="line">        HttpServletRequest request =attributes.getRequest();</span><br><span class="line">        <span class="comment">//记录请求内容</span></span><br><span class="line">        logger.info(<span class="string">"URL :"</span> + request.getRequestURL().toString());</span><br><span class="line">        logger.info(<span class="string">"IP :"</span> + request.getRemoteAddr());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义何时织入————when: @AfterReturning()是在controller方法执行return之后再切入:</span></span><br><span class="line">    <span class="comment">//returning的值ret就是controller方法return的内容</span></span><br><span class="line">    <span class="comment">//@AfterReturning() 可用于对返回值做处理</span></span><br><span class="line">    <span class="meta">@AfterReturning</span>(returning = <span class="string">"ret"</span>, pointcut = <span class="string">"webLog()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doAfterReturning</span><span class="params">(Object ret)</span></span>&#123;</span><br><span class="line">        <span class="comment">// 处理完请求，返回内容</span></span><br><span class="line">        logger.info(<span class="string">"RESPONSE :"</span> + ret);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果如下：<br><img src="/blog/images/20191230094023151.jpg" alt="AOP运行结果"></p>
<ol start="7">
<li><p>AOP的主要名称概念</p>
<blockquote>
<p>Aspect: 通用功能的代码实现。如上面的RequestLogAspect类<br>Target：被织入Aspect的对象。如上面的HelloController<br>Join Point: 即可切入的点，指可以作为切入点的机会，所有方法的执行处都可以作为切入点。如上面的hello()方法<br>Pointcut: 即切入点，Spring支持的切入点就是方法调用。具体定义Aspect实际被应用在的Join Point，支持正则，如上面的webLog()<br>Advice: 是类里的方法以及这个方法如何织入到目标方法的方式，如上面的@Before、@AfterReturning<br>Weaving: 织入，即在AOP的实现过程，将切面应用到实际对象中，从而创建一个代理对象的过程。对Spring来说，就是初始化Context的对象时，完成织入操作。</p>
</blockquote>
</li>
<li><p>Advice的五大种类(根据织入到目标方式的不同划分)</p>
<blockquote>
<p>a. Before(前置通知)：<br>b. AfterReturning(后置通知)<br>c. AfterThrowing(异常通知)<br>d. After(最终通知)<br>e. Around(环绕通知)</p>
</blockquote>
</li>
</ol>
<h2 id="SpringAOP的原理"><a href="#SpringAOP的原理" class="headerlink" title="SpringAOP的原理"></a>SpringAOP的原理</h2><blockquote>
<p>AOP的实现原理：通过JdkProxy或Cglib生成代理对象，具体使用哪种方式，是由AopProxyFactory根据AdvisedSupport对象的配置来决定。 默认策略：如果目标类是接口，则使用JDKProxy来生成，否则用后者生成。</p>
</blockquote>
<ol>
<li>JdkProxy与Cglib的比较</li>
</ol>
<table>
<thead>
<tr>
<th>比较</th>
<th>JDKProxy</th>
<th>Cglib</th>
</tr>
</thead>
<tbody><tr>
<td>底层实现原理</td>
<td>通过Java的内部反射机制实现</td>
<td>以继承的方式动态生成目标类的代理，底层是借助ASM实现(Cglib通过修改字节码实现动态代理)</td>
</tr>
<tr>
<td>说明</td>
<td>JDKProxy通过反射来接收被代理的类，并且要求被代理的类必须实现一个接口</td>
<td>如果目标类没有实现接口，则SpringAOP就会选择使用Cglib动态代理目标类；Cglib可以在运行时动态生成某个类的子类；以继承的方式动态生成目标类的代理。如何某个类被修饰为final，则其无法使用Cglib来做动态代理的。</td>
</tr>
<tr>
<td>核心</td>
<td>JDKProxy的核心： InvocatioHandler接口和Proxy类</td>
<td></td>
</tr>
<tr>
<td>优缺点</td>
<td>反射机制在生成类的过程中比较高效</td>
<td>ASM在生成类之后的执行过程中比较高效</td>
</tr>
</tbody></table>
<ol start="2">
<li>AOP使用了代理模式： 接口 + 真实实现类 +代理类<blockquote>
<p>通过支付宝支付接口讲解AOP的代理模式，其中接口和代理类的实现代码如下：</p>
</blockquote>
</li>
</ol>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Payment</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">pay</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 用户只关心支付功能</span></span><br><span class="line"><span class="comment"> * 背后的取钱、转账操作由AliPay实现，它是作为代理存在的</span></span><br><span class="line"><span class="comment"> * 因为AliPay是代理，所以也要实现接口</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">AliPay</span> <span class="title">implements</span> <span class="title">Payment</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//因为AliPay是代理，所以代替RealPayment的实例</span></span><br><span class="line">    <span class="keyword">private</span> Payment payment;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AliPay</span>(<span class="params">Payment payment</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.payment = payment;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">beforePay</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"从银行取款"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//完整的支付流程</span></span><br><span class="line">    @Override</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pay</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        beforePay();</span><br><span class="line">        payment.pay(); <span class="comment">//调用RealPayment的用户支付</span></span><br><span class="line">        afterPay();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPay</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"支付给慕课网"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果如下图：<br><img src="/blog/images/20191230105413609.jpg" alt="AOP运行结果"></p>
<ol start="4">
<li>Spring里AOP的代理模式的实现方式<blockquote>
<p>真实实现类的逻辑包含在了getBean()方法里<br>getBean()方法返回的实际上是Proxy的实例<br>Proxy的实例是Spring采用JDKProxy或Cglib动态生成的。<br>getBean()方法用于查找或实例化Spring容器中的bean，这也是Spring AOP为什么只能作用于Spring容器中的Bean上的原因，对于不是使用IOC容器管理的Bean对象，SpringAOP是无能为力的</p>
</blockquote>
</li>
</ol>
<p>Spring里AOP的代理模式的实现方式的源码分析：<br><img src="/blog/images/20191230111047099.jpg" alt="Spring里AOP的代理模式的实现方式"></p>
<h2 id="Spring事务的相关面试点"><a href="#Spring事务的相关面试点" class="headerlink" title="Spring事务的相关面试点"></a>Spring事务的相关面试点</h2><p>ACID<br>隔离级别<br>事务传播</p>
<h2 id="本章小结"><a href="#本章小结" class="headerlink" title="本章小结"></a>本章小结</h2><p><img src="/blog/images/20191230111549489.jpg" alt="本章小结"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Java面试/" rel="tag"># Java面试</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/20/how-to-compression-ajax-data/" rel="next" title="解决ajax请求后台大量数据时前端页面加载缓慢的问题">
                <i class="fa fa-chevron-left"></i> 解决ajax请求后台大量数据时前端页面加载缓慢的问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/22/hadoop3.0-step-by-step-1/" rel="prev" title="【一】快速入门Hadoop3.0大数据处理——Hadoop3.0整体概述">
                【一】快速入门Hadoop3.0大数据处理——Hadoop3.0整体概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring家族的介绍"><span class="nav-number">1.</span> <span class="nav-text">Spring家族的介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring-IOC原理"><span class="nav-number">2.</span> <span class="nav-text">Spring IOC原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是DI"><span class="nav-number">2.1.</span> <span class="nav-text">什么是DI</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是IOC"><span class="nav-number">2.2.</span> <span class="nav-text">什么是IOC</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Spring-IOC容器"><span class="nav-number">2.3.</span> <span class="nav-text">Spring IOC容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Bean实例如何装载到IOC容器中"><span class="nav-number">2.4.</span> <span class="nav-text">Bean实例如何装载到IOC容器中</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SpringIOC的refresh源码解析"><span class="nav-number">2.5.</span> <span class="nav-text">SpringIOC的refresh源码解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SpringIOC的getBean方法的解析"><span class="nav-number">2.6.</span> <span class="nav-text">SpringIOC的getBean方法的解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SpringIOC相关面试题"><span class="nav-number">2.7.</span> <span class="nav-text">SpringIOC相关面试题</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AOP的介绍和使用"><span class="nav-number">3.</span> <span class="nav-text">AOP的介绍和使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringAOP的原理"><span class="nav-number">4.</span> <span class="nav-text">SpringAOP的原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring事务的相关面试点"><span class="nav-number">5.</span> <span class="nav-text">Spring事务的相关面试点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本章小结"><span class="nav-number">6.</span> <span class="nav-text">本章小结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
